package p0;

import java.util.Arrays;

/**
 * @author pengjz <br>
 * @version <br>
 * @name Leetcode_14 <br>
 * @date 2020/5/30 0:42<br>
 */
public class Leetcode_16 {
    public static int threeSumClosest(int[] nums, int target) {
        if (nums.length == 3) {
            return nums[0] + nums[1] + nums[2];
        }
        int n = nums.length;
        Arrays.sort(nums);
        int res = nums[0] + nums[1] + nums[2];
        for (int i = 0; i < n - 2; i++) {
            // 需要和前一个数不同
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            for (int j = i + 1; j < n - 1; j++) {
                // 需要和前一个数不同
                if (j > i + 1 && nums[j] == nums[j - 1]) {
                    continue;
                }
                for (int k = j + 1; k < n; k++) {
                    if (Math.abs(nums[i] + nums[j] + nums[k] - target)
                            < Math.abs(res - target)) {
                        res = nums[i] + nums[j] + nums[k];
                        if (res == target) {
                            return res;
                        }
                    }
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{-1, 0, 1, 1, 55}, 3));
    }
}
